package com.jams.goodox.activity.serve.headhunter;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.constant.UamaPayCode;
import com.jams.goodox.entity.ResumeBean;
import com.jams.goodox.entity.StringBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.pay.BalancePayBean;
import com.jams.goodox.entity.resp.ResumeListResp;
import com.jams.goodox.listen.PayListener;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.HeadHunterService;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DialogUtils;
import com.jams.goodox.utils.ProgressDialogUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.UamaPayUtils;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.SimpleDividerItemDecoration;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 企业招聘的简历库
 * <p>
 * create by 顾佳佳 on 2017/05/16
 */
public class ResumeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    View rootView;
    @Bind(R.id.fl_search)
    FrameLayout flSearch;
    @Bind(R.id.rcv_resume)
    RefreshRecyclerView rcvResume;
    @Bind(R.id.swf_resume)
    SwipeRefreshLayout swfResume;
    @Bind(R.id.empty_view)
    LoadView emptyView;

    private double balance;//余额
    private List<ResumeBean> dataList;
    private int curPage;
    private ResumeBean resumeBean;

    public ResumeFragment() {
        // Required empty public constructor
    }

    public static ResumeFragment newInstance() {
        ResumeFragment fragment = new ResumeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_resume, container, false);
            ButterKnife.bind(this, rootView);
            init();
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void init() {
        dataList = new ArrayList<>();
        swfResume.setOnRefreshListener(this);
        rcvResume.setLayoutManager(new RefreshLinearLayoutManager(getContext()));
        rcvResume.setAdapter(new RecycleCommonAdapter<ResumeBean>(getContext(), dataList, R.layout.resume_valid_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, ResumeBean item, int position) {
                setData(helper, item, position);
            }
        });
        rcvResume.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                getResumeList();
            }
        });
        rcvResume.addItemDecoration(new SimpleDividerItemDecoration(getContext()));
        onRefresh();
    }

    //设置数据
    private void setData(RecycleCommonViewHolder helper, final ResumeBean item, final int position) {
        if (item.getOrderStatus() == 0) {
            //有效
            helper.setText(R.id.resume_valid_name, item.getPositionName())
                    .setText(R.id.resume_valid_money, item.getSalary())
                    .setText(R.id.resume_valid_candidate, item.getName())
                    .setText(R.id.resume_valid_work, item.getJobLife())
                    .setText(R.id.resume_valid_major, item.getMajor())
                    .setText(R.id.resume_valid_referrer, "推荐人：" + item.getRecommendName())
                    .setText(R.id.resume_valid_referrer_money, "奖励金额：" + item.getReward()+"元")
                    .setViewVisible(R.id.ll_invalid_group, false)
                    .setViewVisible(R.id.rl_valid_group, true);
            //根据本地保存的状态来判断显示状态
            switch (item.getActionType()) {
                case 0://未操作
                    helper.getView(R.id.rl_action_group).setVisibility(View.VISIBLE);
                    helper.getView(R.id.iv_resume_status).setVisibility(View.GONE);
                    break;
                case 1://1不匹配
                    helper.getView(R.id.rl_action_group).setVisibility(View.INVISIBLE);
                    helper.getView(R.id.iv_resume_status).setVisibility(View.VISIBLE);
                    helper.getView(R.id.iv_resume_status).setBackgroundResource(R.mipmap.resume_un_match);
                    break;
                case 2://2已支付
                    helper.getView(R.id.rl_action_group).setVisibility(View.INVISIBLE);
                    helper.getView(R.id.iv_resume_status).setVisibility(View.VISIBLE);
                    helper.getView(R.id.iv_resume_status).setBackgroundResource(R.mipmap.resume_pay);
                    break;
                default:
                    helper.getView(R.id.rl_action_group).setVisibility(View.VISIBLE);
                    helper.getView(R.id.iv_resume_status).setVisibility(View.GONE);
                    break;
            }
        } else if (item.getOrderStatus() == 1 || item.getOrderStatus() == 2) {
            //已支付 不匹配
            helper.setText(R.id.resume_invalid_referrer, item.getRecommendName())
                    .setText(R.id.resume_invalid_candidate, item.getName())
                    .setText(R.id.resume_invalid_money, item.getReward() + "元")
                    .setViewVisible(R.id.ll_invalid_group, true)
                    .setViewVisible(R.id.rl_valid_group, false);
            if (position == 0) {//没有有效的
                helper.setViewVisible(R.id.rl_invalid_hint_group, true);
            } else {
                if (dataList.get(position - 1).getOrderStatus() == 0) {
                    helper.setViewVisible(R.id.rl_invalid_hint_group, true);
                } else {
                    helper.setViewVisible(R.id.rl_invalid_hint_group, false);
                }
            }
        }

        helper.setOnItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                //1、2表示是过期的   ，actionType 0表示是未操作
                if(item.getOrderStatus() == 1 || item.getOrderStatus() == 2 || item.getActionType() != 0){
                    return;
                }
                Intent intent = new Intent(getContext(), ResumeDetailActivity.class);
                intent.putExtra(ResumeDetailActivity.ID, item.getResumeId());
                qStartActivity(intent);
            }
        });
        helper.getView(R.id.tv_un_matching).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtils.deleteConfirm(getActivity(), "确定该简历不匹配？", new SuccessListener() {
                    @Override
                    public void success() {
                        disable(item, position);
                    }
                });
            }
        });
        helper.getView(R.id.tv_valid_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resumeBean = item;
                requestBalance();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.fl_search)
    public void onViewClicked() {
        Intent intent = new Intent(getContext(), ResumeSearchActivity.class);
        startActivityForResult(intent, 1991);
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                swfResume.setRefreshing(true);
                curPage = 1;
                getResumeList();
            }
        });
    }

    private void getResumeList() {
        User user = DataCacheManager.getInstance().getUser();
        if (user == null) {
            return;
        }
        enqueue(createCallService(HeadHunterService.class).getResumeList(null, user.getEnterpriseId(), curPage, AppConfig.PagSize), new RetrofitCallbackListener<ResumeListResp>() {
            @Override
            public void onSuccess(Call<ResumeListResp> call, ResumeListResp result) {
                swfResume.setRefreshing(false);
                rcvResume.loadMoreComplete();
                if (result.getData() != null && result.getData().getResultList() != null) {
                    if (curPage == 1) {
                        dataList.clear();
                    }
                    if (result.getData().getPageInfo() == null) {
                        rcvResume.setCanLoadMore(false);
                    } else {
                        rcvResume.setCanLoadMore(result.getData().getPageInfo().isHasMore());
                    }
                    dataList.addAll(result.getData().getResultList());
                    curPage++;
                    rcvResume.notifyData();
                }
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_resume,"暂无简历");
                } else {
                    emptyView.loadComplete();
                }
            }

            @Override
            public void onError(String msg) {
                swfResume.setRefreshing(false);
                rcvResume.loadMoreComplete();
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_resume,"暂无简历");
                } else {
                    emptyView.loadComplete();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1991 && resultCode == 1992) {
            onRefresh();
        }
    }

    //不匹配
    private void disable(final ResumeBean resumeBean, final int position) {
        ProgressDialogUtils.show(getContext(), "");
        enqueue(createCallService(HeadHunterService.class).disableResume(resumeBean.getId()), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                ProgressDialogUtils.dismiss();
                resumeBean.setActionType(1);
                rcvResume.notifyData();
            }

            @Override
            public void onError(String msg) {
                ProgressDialogUtils.dismiss();
            }
        });
    }

    /**
     * 请求最新余额数据
     */
    public void requestBalance() {
        if(DataCacheManager.getInstance().getUser().getEnterpriseAdminId() == null){
            return;
        }
        enqueue(createCallService(MineService.class).balance(DataCacheManager.getInstance().getUser().getEnterpriseAdminId()), new RetrofitCallbackListener<StringBean>() {
            @Override
            public void onSuccess(Call<StringBean> call, StringBean result) {
                try {
                    balance = Double.parseDouble(result.getData());
                } catch (NumberFormatException e) {
                    balance = 0.00;
                }
                if (balance < resumeBean.getReward()) {
                    ToastUtil.show(getString(R.string.company_money_unenough));
                    return;
                }
                BalancePayBean balancePayBean = new BalancePayBean();
                balancePayBean.setBalance(StringUtils.doubleToString(balance));
                balancePayBean.setType(2);//直接设置企业订单
                balancePayBean.setOrderId(resumeBean.getId());
                balancePayBean.setUserId(DataCacheManager.getInstance().getUser().getEnterpriseAdminId());
                balancePayBean.setPaySubCode(StringUtils.toString(Constants.HeadHunter_Code));//简历库subCode
                UamaPayUtils.payByBalance(getActivity(), balancePayBean, new PayListener() {
                    @Override
                    public void payResult(int status, String msg) {
                        switch (status) {
                            case UamaPayCode.PAY_SUCCESS:
                                resumeBean.setActionType(2);
                                rcvResume.notifyData();
                                break;
                            case UamaPayCode.BALANCE_CHANGE:
                                ToastUtil.show(TownApplicationLike.getInstance(),"订单支付失败，您的账户可能存在多人操作，导致余额变动，请重新支付。");
                                break;
                            case UamaPayCode.PAY_ERROR:
                                ToastUtil.show("支付失败");
                                break;
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {
                balance = 0.00;
            }
        });
    }
}
